package com.aididi.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *      自定义GlobalFilter
 * @Auther: zx.xu
 * @Description:    自定义全局过滤器，不需要在配置文件中配置，作用在所有的路由上
 *   此GlobalFilter用来校验请求中是否包含了请求参数如“token”，
 *   如何不包含请求参数“token”则不转发路由，否则执行正常的逻辑
 */
@Slf4j
public class TokenGlobalFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数token
        String queryParams = exchange.getRequest().getHeaders().getFirst("token");
        if(queryParams ==null || queryParams.isEmpty()){
            log.info("token is empty..");
            //如果token为空，无权访问
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();

        }
        log.info("ending...");
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
